package com.example.demo.web;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;


@RequestMapping("user")
@Controller
public class UserController {

    @Autowired
    private UserService userService;


    @ResponseBody
    @PostMapping("list")
    public List<User> list(User userParams,
                           @RequestParam(defaultValue = "1") int pageNum,
                           @RequestParam(defaultValue = "10") int pageSize) {

        return userService.listUsers(userParams, pageNum, pageSize);

    }

    @RequestMapping("delete/{userId}")
    @ResponseBody
    public String delete(@PathVariable("userId") long userId) {
        boolean result = userService.deleteUser(userId);
        if (result) {
            return "success";
        }
        return "Delete user(" + userId + ") failed!";

    }


    @PostMapping("save")
    @ResponseBody
    public String save(@Valid User user) {
        return userService.saveUser(user);
    }


    /*
     * @Params userParams: userId必填
     * */
    @ResponseBody
    @PostMapping("update")
    public String update(User userParams) {
        Long userId = userParams.getUserId();
        if (userId == null || userId < 0) {
            return "Missing user id!";
        }
        return userService.updateUser(userParams);
    }


}


